package mrusanov.ui.management.buildings

import javax.swing.{JButton, JLabel, JPanel}
import mrusanov.buildings.Building
import net.miginfocom.swing.MigLayout
import mrusanov.localization.Localization
import java.awt.event.{ActionEvent, ActionListener}

abstract class AbstractBuildingPanel(building:Building) extends JPanel {
  setLayout(new MigLayout("fill"))

  private val levelLabel = new JLabel()
  private val usageLevelLabel = new JLabel()
  private val maintenanceCostLabel = new JLabel()
  private val upgradeCostLabel = new JLabel()

  private def updateBuildingInfo() {
    levelLabel.setText(building.buildingLevel.toString)
    usageLevelLabel.setText(building.usageLevel.toString)
    maintenanceCostLabel.setText(building.maintenanceCost.toString)
    upgradeCostLabel.setText(building.upgradeCost.toString)
  }


  add(new JLabel(Localization(buildingNameKey)), "span 2, wrap, align center")
  add(new JLabel(Localization("building.level")))
  add(levelLabel, "wrap")
  add(new JLabel(Localization("building.usageLevel")))
  add(usageLevelLabel, "wrap")
  add(new JLabel(Localization("building.maintenanceCost")))
  add(maintenanceCostLabel, "wrap")
  add(new JLabel(Localization("building.upgradeCost")))
  add(upgradeCostLabel, "wrap")

  val decreaseLevelButton = new JButton()
  val increaseLevelButton = new JButton()

  updateBuildingInfo()
  setButtonsText()

  add(decreaseLevelButton)
  add(increaseLevelButton)

  private def setButtonsText() {
     if (building.usageLevel == building.buildingLevel) {
       increaseLevelButton.setText(Localization("building.upgrade"))
     } else {
       increaseLevelButton.setText(Localization("building.increaseUsageLevel"))
     }

     decreaseLevelButton.setText(Localization("building.decreaseUsageLevel"))
     decreaseLevelButton.setEnabled(building.usageLevel != 0)
  }

  decreaseLevelButton.addActionListener(new ActionListener {
    def actionPerformed(e: ActionEvent) {
      building.usageLevel-=1
      setButtonsText()
      updateBuildingInfo()
    }
  })

  increaseLevelButton.addActionListener(new ActionListener {
    def actionPerformed(e: ActionEvent) {
      if (building.usageLevel ==  building.buildingLevel) {
        building.increaseLevel()
      } else {
        building.usageLevel += 1
      }

      updateBuildingInfo()
      setButtonsText()
    }
  })

  def buildingNameKey:String
}
